using HeshaNAuth;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        private readonly HeshaNAuth.HeshaNAuth auth = new HeshaNAuth.HeshaNAuth();
        private const string AppVersion = "1.1.1";  // your current app version
        private readonly string DefaultAdminKey = "ebhwsebebeeb"; // your admin key here

        private CancellationTokenSource _rtGuardCts;

        public Form1()
        {
            InitializeComponent();

            
            this.Load += Form1_Load;
        }

      
        private void PromptUpdateAndExit(string required, string url)
        {
            var msg =
                $"This app is out of date.\n" +
                $"Required: {required ?? "(unknown)"}\n" +
                $"You have: {AppVersion}\n\n" +
                $"Do you want to update now?";

            var choice = MessageBox.Show(
                msg,
                "Update required",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button1);

            if (choice == DialogResult.Yes)
            {
                if (!string.IsNullOrWhiteSpace(url))
                {
                    HeshaNAuth.HeshaNAuth.OpenUrl(url);
                }
                else
                {
                    MessageBox.Show("No update link is configured.", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            Application.Exit();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            
            var (isValid, required, url) = await HeshaNAuth.HeshaNAuth.CheckAppVersionAsync(DefaultAdminKey, AppVersion);
            if (!isValid)
            {
                PromptUpdateAndExit(required, url);
                return;
            }

            
            _rtGuardCts = new CancellationTokenSource();

            void OnMismatch(string req, string link)
            {
                // Ensure UI thread
                if (!IsDisposed)
                {
                    BeginInvoke(new Action(() =>
                    {
                        PromptUpdateAndExit(req, link);
                    }));
                }
            }

            _ = HeshaNAuth.HeshaNAuth.StartRealtimeVersionGuardAsync(
                adminKey: DefaultAdminKey,
                appVersion: AppVersion,
                onMismatch: OnMismatch,
                ct: _rtGuardCts.Token
            );
        }

        private async void LoginButton_Click(object sender, EventArgs e)
        {
       
            var (isValid, required, url) = await HeshaNAuth.HeshaNAuth.CheckAppVersionAsync(DefaultAdminKey, AppVersion);
            if (!isValid)
            {
                PromptUpdateAndExit(required, url);
                return;
            }

            bool ok = await auth.AuthenticateAndSaveHWIDAsync(
                txtUsername.Text.Trim(), // username textbox
                txtPassword.Text,  // password textbox
                DefaultAdminKey,
                AppVersion
            );

            if (ok)
            {
                MessageBox.Show("Login successful!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // continue
            }
            else
            {
                MessageBox.Show("Login failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _rtGuardCts?.Cancel();
            base.OnFormClosing(e);
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            lblRegStatus.Text = "Registering..."; // label here
            button2.Enabled = false;

            try
            {
                string token = txtRegToken.Text.Trim(); // token textbox
                string username = txtRegUsername.Text.Trim(); // username textbox
                string password = txtRegPassword.Text; // password textbox

                var (ok, err) = await auth.RegisterUserWithTokenAsync(token, username, password, DefaultAdminKey);

                if (ok)
                {
                    MessageBox.Show("Registered successfully! You can now log in.",
                        "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    lblRegStatus.Text = "Registration complete!";
                }
                else
                {
                    lblRegStatus.Text = err ?? "Registration failed.";
                }
            }
            finally
            {
                button2.Enabled = true;
            }
        }
    }
}
